import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Hero } from './hero';
import { Observable } from 'rxjs/Observable';
import { catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

const httpOptions = {
    headers: new HttpHeaders({
        'Content-type': 'application/json',
        'Authorization': 'my-auth-token'
    })
};

const apiurl = 'api/heroes';

@Injectable()
export class HeroesService {
    heroesUrl = '';
    constructor(
        private http: HttpClient
    ) {}

    getHeroes() {
        return this.http.get<Hero[]>(apiurl)
            .pipe(
                catchError(this.handleError('getHeroes', []))
            );
    }

    getHero(id: number|string) {
        const url = `${apiurl}/${id}`;
        return this.http.get<Hero>(url).pipe(
            tap(_ => console.log(`fetch id ${id}`)),
            catchError(this.handleError<Hero>(`getHero id = ${id}`))
        );
    }

    /**
     * Handle Http operation that failed.
     * Let the app continue.
     * @param operation - name of the operation that failed
     * @param result - optional value to return as the observable result
     */
    private handleError<T> (operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {

        // TODO: send the error to remote logging infrastructure
        console.error(error); // log to console instead

        // Let the app keep running by returning an empty result.
        return of(result as T);
        };
    }

    // addHero(hero: Hero): Observable<Hero> {
    //     return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    //             .pipe(
    //                 catchError(this.handleError('addHero', hero));
    //             );
    // }

    // deleteHero(id: number): Observable<{}> {
    //     const url = `${this.heroesUrl}/${id}`;
    //     return this.http.delete(url, httpOptions)
    //             .pipe(
    //                catchError(this.handleError('deleteHero'))
    //             );
    // }

    // updateHero(hero: Hero): Observable<Hero> {
    //     return this.http.put(this.heroesUrl, hero, httpOptions)
    //             .pipe(
    //                 catchError(this.handleError('updateHero', hero))
    //             );
    // }

    // 添加 url 参数
    // searchHeroes(term: string): Observable<Hero[]> {
    //     term = term.trim();

    //     const options = term ? { params: new HttpParams().set('name', term) } : {};

    //     return this.http.get<Hero[]>(this.heroesUrl, options)
    //             .pipe(
    //                 catchError(this.handleError('searchHeroes', []))
    //             );
    // }


}
